<?php

namespace app\Modules\Api\models;

use Yii;
use app\models\User as BaseModel;

/**
 * LoginForm is the model behind the login form.
 *
 * @property user|null $user This property is read-only.
 * @property Product[] $collects This property is read-only.
 */
class User extends BaseModel
{
    public function fields()
    {
        $fields = parent::fields();
        $fields['img'] = function (){
            $img = $this->img?$this->img:'default_photo.jpg';
            return Yii::$app->params['uploadUrl'].$img;
        };
        $strvalfields = ['userid','sex','take_money','give_money','type','phone_type'];

        foreach($strvalfields as $strvalfield){
            $fields[$strvalfield] = function() use ($strvalfield){
                return strval($this->$strvalfield);
            };
        }
        unset($fields['created_at'],$fields['updated_at']);
        return $fields;
    }

    /**
     * @return yii\db\ActiveQuery
     */
    public function getCollects()
    {
        return $this->hasMany(Product::className(),['pid'=>'product_id'])
            ->viaTable('collect',['user_id'=>'userid'],function($query){
                /** @var $query yii\db\ActiveQuery */
                $query->addOrderBy(['collectid'=>SORT_DESC]);
            });
    }

    public function getLevel()
    {
        $sort = explode(',',$this->sort);
        return count($sort);
    }
}